import { isExternal } from "../_utils/url";
import { AppContext } from "../AppProvider";
import { message, UploadProps } from "antd";
import { useContext, useEffect, useRef, useState } from "react";

const useUploadProps = (props): UploadProps => {
    const { onChange, maxCount, onFileNameChange, fileName, dataType = 'string', value, onResponse, ...rest } = props
    const { fileBasicUrl='', upload = { action: '' }, apiPrefix, commonHeaders } = useContext(AppContext)
    let action = props.action || upload.action
    if (apiPrefix && !isExternal(action)) {
        action = `${apiPrefix}${action}`
    }
    const fileKey =upload.fileKey|| "fileStorageName";
    const showFileName = useRef<any>([]);
    const [fileList, setFileList] = useState([]);
    const normalFileName = (item: any, index: number) => {

        if (showFileName.current && showFileName.current[index]) {
            return showFileName.current[index]
        } else if (typeof item === 'object') {
            return item['fileOriginName']
        }
        return item

    }
    const normalFileUrl = (item: any) => {
        return (typeof item == 'object' && item !== null) ? item.fileUrl : item
    }
    useEffect(() => {
        let _fileName =
            typeof fileName === "string"
                ? (fileName || "").split(",").filter(Boolean)
                : fileName;
        showFileName.current = _fileName;
    }, [fileName]);
    useEffect(() => {
        if (value) {
            // console.log('valuevalue', value)
            let _value = [];
            if (dataType === 'string') {
                _value = value.split(",").filter(Boolean);

            } else {

                _value = value
            }
            console.log({ _value })
            // let _fileName = typeof fileName === 'string' ? (fileName||'').split(',').filter(Boolean) : fileName;
            setFileList(
                _value.filter(Boolean).map((item: string, index: number) => {

                    const url:string = normalFileUrl(item)
                  
                    return {
                        // thumbUrl:baseApi+ '/wineshop/file/downFile?filePath='+url,
                        thumbUrl: isExternal(url)?url: fileBasicUrl + url,
                        name: normalFileName(item, index),
                        // status:url.startsWith('blob:')?'uploading':undefined,
                        // 防止更新时候，没有uid，uploading->done会闪烁
                        uid: fileList[index]?.uid || url,
                        url: url,
                    };
                })
            );
        }
    }, [value])
    const noticeChange = (files: any[]) => {

        if (onChange) {
            //   if (!showUploadList) {
            //     return onChange(info);
            //   }
            // console.log('files11', files)
            let _files = files.map((item) => {

                let url = '';
                if (item.url) {
                    url = item.url;
                } else if (item.status === "uploading") {
                    url = ''
                } else if(item.response) {

                    url = item.response.data[fileKey as string]
                    //   if(props.picName){

                    //     form.setFieldValue(props.picName,item.response.data['picName'])
                    //   }
                }
                if (dataType == 'fileNameInValue') {
                    return {
                        fileUrl: url,
                        fileOriginName: item.name
                    }
                }
                return url
            }).filter(v => {
                return typeof v === 'string' ? v : v.fileUrl
            });
            onFileNameChange && onFileNameChange(showFileName.current);
            // console.log('_files_files', _files)
            if (fileList.length === _files.length) {
                onChange(dataType === "array" ? _files : _files.join(","));

            }
            //   @ts-ignore
        }
    };
    const _onChange = (e) => {
        setFileList(v => {

            const item = v.find(vv => vv.uid == e.file.uid);
            // const item = v[index]
            if (v.length > maxCount) {
                v.splice(maxCount - 1, 1);
                if (Array.isArray(showFileName.current)) {
                    showFileName.current.splice(maxCount - 1, 1);
                }
            } else if (item) {
                
                if (e.file.status == 'done') {
                    if (onResponse) {
                        onResponse(e.file.response)
                        return
                    }
                    if(e.file.response.code==200){

                        item.url = e.file.response.data[fileKey]
                    }else{
                        const index = v.findIndex(vv=>vv.uid == e.file.uid);
                        console.log('删除',index)
                        if(index>-1){
                            console.log('删除',index)
                            v.splice(index,1)
                        }
                        console.log('删除',JSON.stringify(v))
                        message.error( e.file.response.msg)
                    }
                }else if(e.file.status == 'error'){
                    const index = v.findIndex(vv=>vv.uid == e.file.uid)
                    console.log('删除2',index)
                    if(index>-1){
                        v.splice(index,1)
                    }
                    message.error( '上传错误')   
                } 

                // Object.assign(item, { ...e.file })
                // if (e.file.originFileObj) {
                //     item.url = URL.createObjectURL(e.file.originFileObj)
                // }
            } else {
                if (Array.isArray(showFileName.current)) {
                    showFileName.current.push(e.file.name);
                }
                v.push({
                    ...e.file,
                    // url: URL.createObjectURL(e.file.originFileObj)
                })
            }
            console.log('JSON.stringify',JSON.stringify(v))
            console.log('itemitem',v, e, item)
            noticeChange(v)
            return v
        })
    }
    const onRemove = (file) => {

        let findIndex = fileList.findIndex((item: { uid: any; }) => item.uid === file.uid);
        if (findIndex > -1) {
            fileList.splice(findIndex, 1);
            console.log(showFileName, "showFileName");
            if (Array.isArray(showFileName.current)) {
                showFileName.current.splice(findIndex, 1);
            }
        }
        noticeChange(fileList);
    }
    const onPreview = (e: { thumbUrl: string | URL; }) => {
        window.open(e.thumbUrl)
    }
    return {
        headers: commonHeaders,
        multiple: true,
        action,
        onPreview,
        onRemove,
        fileList,
        onChange: _onChange,
        ...rest
    }
}
export default useUploadProps